package com.argrace.smart.thread;

import android.os.SystemClock;
import android.util.Log;

import com.argrace.smart.util.Logg;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * Created by argrace_dev_1 on 2018/1/29.
 */

public class MyRecieveUdpThread implements Runnable {
    private String add = null;

    private int port = 0;
    private RecieveUdpThreadCallBack callBack;
    private boolean is_continue = true;
    MulticastSocket ms;

    public MyRecieveUdpThread(String add, int port, RecieveUdpThreadCallBack callBack) {
        this.add = add;
        this.port = port;
        this.callBack = callBack;
    }

    @Override
    public void run() {
        Logg.i("info", "启动了recieveListeners");
        byte[] data = new byte[4096];
        while (is_continue) {
            Logg.i("info", "监听中....");
            try {
                InetAddress groupAddress = InetAddress.getByName(add);
                ms = new MulticastSocket(port);
                ms.joinGroup(groupAddress);
                DatagramPacket dp = new DatagramPacket(data, data.length);
                if (ms != null) {
                    ms.receive(dp);
                }
                String quest_ip = dp.getAddress().toString();
                String codeString = new String(dp.getData(), 0, dp.getLength()).trim();
                callBack.callBack(codeString);
                Logg.i("info", "收到来自" + quest_ip + "的请求,内容:" + codeString);
                is_continue = false;
            } catch (Exception e) {

            }
        }
        if (ms != null) {
            ms.close();
        }


    }

    public interface RecieveUdpThreadCallBack {
        public void callBack(String msg);
    }
}
